package com.ym.core.shiro;


import com.ym.common.constant.UserDetails;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: zhangfengzhou
 * Date: 2019-04-04
 * Time: 16:05
 */
public class ShiroUtil {

	public static Subject getSubject() {
		try {
			return SecurityUtils.getSubject();
		} catch (Exception e) {
			return null;
		}
	}

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static String getIp() {
		return getSubject().getSession().getHost();
	}

	public static String getSessionId() {
		return String.valueOf(getSubject().getSession().getId());
	}

	public static void setLoginUser(UserDetails user) {
		Subject subject = getSubject();
		PrincipalCollection principalCollection = subject.getPrincipals();
		String realmName = principalCollection.getRealmNames().iterator().next();
		PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);
		// 重新加载Principal
		subject.runAs(newPrincipalCollection);
	}

	public static void logout() {
		getSubject().logout();
	}

	public static <T extends UserDetails> T getLoginUser(Class<T> cls, boolean... catchException) {
		try {
			T user = getSubject().getPrincipals().oneByType(cls);
			return user;
		} catch (Exception e) {
			if (catchException.length > 0 && catchException[0]) {
				return null;
			} else {
				throw new ExpiredCredentialsException();
			}
		}
	}

	public static UserDetails getLoginUser(boolean... catchException) {
		try {
			UserDetails sysUser = getSubject().getPrincipals().oneByType(UserDetails.class);
			return sysUser;
		} catch (Exception e) {
			if (catchException.length > 0 && catchException[0]) {
				return null;
			} else {
				throw new ExpiredCredentialsException();
			}
		}
	}


	/**
	 * 获取登录人的ID
	 *
	 * @return
	 */
	public static Long getLoginId(boolean... catchException) {
		UserDetails user = getLoginUser(catchException);
		return user == null ? null : user.getId();
	}

	/**
	 * 获取登录人账号
	 *
	 * @return
	 */
	public static String getLoginAccount(boolean... catchException) {
		UserDetails user = getLoginUser(catchException);
		return user == null ? null : user.getAccount();
	}

	/**
	 * 获取加密密码
	 *
	 * @param pwd
	 * @param salt
	 * @return
	 */
	public static String genHashPass(String pwd, String salt) {
		String hashedPwd = new Sha256Hash(pwd, salt, 1024).toBase64();
		return hashedPwd;
	}

	public static void main(String[] args) {
		System.out.println(genHashPass("123456", "3c930d32915f4f7eb04fdec9afad951d"));
	}


}
